<template>
  <div>
     <el-row>
      <el-col :span="3"> 
        <el-input v-model="ser.name" placeholder="请输入角色名称"></el-input>
      </el-col>
      <el-col :span="20">
        <el-button @click="specification_click" icon="el-icon-search"  class="add_btn"> 搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          @click="specification_clicks"
          class="add_btn">
          重置</el-button>
        <el-button @click="add_role" icon="el-icon-plus" class="add_btn">新增角色</el-button>
      </el-col>
    </el-row>
     <el-table :data="dataList" stripe style="width: 100%" border>
       <el-table-column prop="name" label="角色">
       </el-table-column>
       <el-table-column  label="状态">
         <template slot-scope="scope" >
           <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
             :inactive-value="2"  @change='switch_change(scope.row.status,scope.row.id)'>
           </el-switch>
         </template>
       </el-table-column>
       <el-table-column label="操作" width="300">
         <template slot-scope="scope">
           <el-button @click="set_role(scope.row)" type="text" icon="el-icon-edit">编辑</el-button>
           <el-button size="mini" type="text" icon="el-icon-edit"  @click="setRoles(scope.row)">分配菜单权限</el-button>
           <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
             title="是否删除这条数据？" @confirm="del_product(scope.row)">
             <el-button slot="reference" type="text" icon="el-icon-delete"> 删除</el-button>
           </el-popconfirm>
         </template>
       </el-table-column>
     </el-table>
     <div class="pagination">
       <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background @prev-click='prev'
         @next-click='next' :current-page.sync="pagination.page" :page-size="pagination.per_page"
         layout="total, prev, pager, next" :total="total">
       </el-pagination>
     </div>


     <el-dialog :title="title" :visible.sync="isProduct" width="30%" @close="dialog_close">
       <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
         <el-form-item label="姓名" prop="name">
           <el-input v-model="ruleForm.name"></el-input>
         </el-form-item>
       </el-form>
       <span slot="footer" class="dialog-footer">
         <el-button @click="isProduct = false">取 消</el-button>
         <el-button type="primary" @click="submitadd('ruleForm')">确定</el-button>
       </span>
     </el-dialog>

    <el-dialog title="分配权限" :visible.sync="setRole_box" width="30%" :close-on-click-modal='false'>
      <el-row>
        <el-col>
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'tree')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'tree')">全选/全不选</el-checkbox>
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'tree')">父子联动
          </el-checkbox>
          <el-tree
            :data="menuOptions"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps">
          </el-tree>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSetRole()">取 消</el-button>
        <el-button type="primary" @click="clickSetRole()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {getRoleList,createRole,getNodeList,allocationNode,getRoleNodeList,setRoleStatus} from '@/api/role/index'
  export default {
    data() {
      return {
        ser:{
          name:''
        },
        menuExpand: false,
        menuNodeAll: false,
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        menuOptions: [],
        form:{},
        defaultProps: {
            children: "children",
            label: "title"
          },
        setRole_box: false,
        title:"",
        isProduct:false,
        dataList: [],
        ruleForm:{
          name:'',
          id:''
        },
        rules:{
          name:[
            {
              required: true,
              message: '请输入用户姓名',
              trigger: 'blur'
            }
          ]
        },
        pagination: {
          per_page:10,
          page: 1,
        },
        total: 0,
        }
      },
      mounted() {
        this.getlist()
        this.getRole()
      },
      methods:{
        /** 查询角色列表 */
        getRole() {
          getNodeList().then(res => {
             this.menuOptions=res.msg.data
          });
        },
          getlist(){
            getRoleList({...this.pagination,...this.ser}).then(res => {
              if (res.code == 200) {
                this.dataList = res.data.data
                this.total = res.data.total
              }
            })
          },
          specification_clicks(){
            
            getRoleList(this.pagination).then(res => {
              if (res.code == 200) {
                this.dataList = res.data.data
                this.total = res.data.total
              }
            })
          },
          specification_click(){
            this.pagination= {
              per_page: 10,
              page: 1
            }
            getRoleList({...this.pagination,...this.ser}).then(res => {
              if (res.code == 200) {
                this.dataList = res.data.data
                this.total = res.data.total
              }
            })
        
          },
          handleSizeChange(val) {
            console.log(val)
            console.log(`每页 ${val} 条`);
          },
          handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.pagination.page = val
            this.getlist()
          },
          prev() {
            this.pagination.page = this.pagination.page - 1
            this.getlist()
          },
          next() {
            console.log('ss')
            this.pagination.page = this.pagination.page + 1
            this.getlist()
          },
          set_role(row){
              this.isProduct=true
              this.title='用户修改'
              this.ruleForm=row
          },
          add_role(){
              this.isProduct=true
              this.title='用户新增'
          },
          submitadd(formName) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                createRole(this.ruleForm).then(res => {
                  if (res.code == 200) {
                    this.isProduct = false
                    this.$message.success('提交成功')
                    this.getlist()
                  }
                })
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          dialog_close(){
              this.$nextTick(function() {
                this.$refs.ruleForm.resetFields()
              })
          },
          switch_change(val, id) {
            let prms = {
              id,
              status: val
            }
            setRoleStatus(prms).then(res => {
              console.log(res)
              if (res.code == 200) {
                this.$message.success('提交成功')
                this.getlist()
              }
            });
          },
          setRoles(row) {
            this.setRole_box=true
            this.getMenuTreeselect(row.id)
            console.log('row',row)
            this.role_id=row.id
          },
          /** 查询菜单树结构 */
          getMenuTreeselect(roleId) {
            let query={
              roles_id:roleId
            }
            getRoleNodeList(query).then(res => {
              this.menuOptions=[] 
              this.menuOptions = res.data;
              console.log(this.menuOptions)
              let arry = this.push_tree(this.menuOptions)
              console.log(arry)
              this.$refs.tree.setCheckedKeys(arry)
            });
          },
          push_tree(arr){
            let arry=[]
            arr.forEach(e=>{
               if(e.is_check==1){
                 arry.push(e.id)
               }
               if(e.children){
                    e.children.forEach(f=>{
                      if(f.is_check==1){
                        arry.push(f.id)
                      }
                      if(f.children){
                          f.children.forEach(g=>{
                            if(g.is_check==1){
                              arry.push(g.id)
                            }
                          })
                      }
                    })
               }else{
                 return false
               }
            })
            return arry
          },
          // 树权限（展开/折叠）
          handleCheckedTreeExpand(value, type) {
            console.log(value)
            if (type == 'tree') {
              let treeList = this.menuOptions;
              for (let i = 0; i < treeList.length; i++) {
                this.$refs.tree.store.nodesMap[treeList[i].id].expanded = value;
              }
            } else if (type == 'dept') {
              let treeList = this.deptOptions;
              for (let i = 0; i < treeList.length; i++) {
                this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
              }
            }
          },
          // 树权限（全选/全不选）
          handleCheckedTreeNodeAll(value, type) {
            if (type == 'tree') {
              this.$refs.tree.setCheckedNodes(value ? this.menuOptions : []);
            } else if (type == 'dept') {
              this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
            }
          },
          // 树权限（父子联动）
          handleCheckedTreeConnect(value, type) {
            if (type == 'tree') {
              this.menuCheckStrictly = value ? true : false;
            } else if (type == 'dept') {
              this.deptCheckStrictly = value ? true : false;
            }
          },
          /** 选择角色权限范围触发 */
          dataScopeSelectChange(value) {
            if (value !== '2') {
              this.$refs.dept.setCheckedKeys([]);
            }
          },
          getDeptAllCheckedKeys() {
            //目前被选中的节点
            let checkedKeys = this.$refs.tree.getCheckedKeys();
            let halfCheckedKeys =  this.$refs.tree.getHalfCheckedKeys();
            checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
               return checkedKeys;
          },
          closeSetRole(){
              this.setRole_box=false
          },
          clickSetRole(){
            var rolesL=this.getDeptAllCheckedKeys()
            console.log(rolesL)
            let query={
              roles_id:this.role_id,
              node_id:rolesL
            }
              allocationNode(query).then(res=>{
                if(res.code==200){
                   this.$message.success('提交成功')
                   this.setRole_box=false
                }
              })

          }

      },
  }

</script>

<style>
</style>
